/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Analisador.Lexico;
import Analisador.Sintatico;
import Util.ListaErro;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Danilo
 */
public class TelaPrincipal extends javax.swing.JFrame {

    private File arquivo;
    private static boolean importouArquivo = false;
    private static boolean executouAnalisadores = false;
    private static String pathSaida;
    private static String nomeArquivo;

    /**
     * Creates new form TelaPrincipal
     */
    public TelaPrincipal() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        buttonConstruir = new javax.swing.JButton();
        panel1 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        textAreaPrincipal = new javax.swing.JTextPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textAreaResultado = new javax.swing.JTextArea();
        buttonLimpar = new javax.swing.JButton();
        buttonCompilar = new javax.swing.JButton();
        buttonSalvar = new javax.swing.JButton();
        label1 = new java.awt.Label();
        caminhoSaida = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();

        fileChooser.setFileFilter(new FiltroTexto());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("DM IDE");
        setResizable(false);

        buttonConstruir.setText("Análise Léxica");
        buttonConstruir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonConstruirActionPerformed(evt);
            }
        });

        textAreaPrincipal.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        jScrollPane3.setViewportView(textAreaPrincipal);

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3)
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE)
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Resultado"));

        textAreaResultado.setEditable(false);
        textAreaResultado.setColumns(20);
        textAreaResultado.setRows(5);
        jScrollPane1.setViewportView(textAreaResultado);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
                .addContainerGap())
        );

        buttonLimpar.setText("Limpar");
        buttonLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLimparActionPerformed(evt);
            }
        });

        buttonCompilar.setText("Análise Sintática");
        buttonCompilar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCompilarActionPerformed(evt);
            }
        });

        buttonSalvar.setText("Salvar");
        buttonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSalvarActionPerformed(evt);
            }
        });

        label1.setText("Diretório de saída:");

        caminhoSaida.setEditable(false);
        caminhoSaida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                caminhoSaidaActionPerformed(evt);
            }
        });

        jMenu1.setText("Arquivo");

        jMenuItem1.setText("Importar...");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ajuda");

        jMenuItem2.setText("Sobre");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 511, Short.MAX_VALUE)
                                .addComponent(buttonSalvar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonLimpar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonCompilar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonConstruir)
                                .addGap(15, 15, 15))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(2, 2, 2)
                        .addComponent(caminhoSaida)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(caminhoSaida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonConstruir)
                    .addComponent(buttonLimpar)
                    .addComponent(buttonCompilar)
                    .addComponent(buttonSalvar))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleDescription("");

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonConstruirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonConstruirActionPerformed
        // TODO add your handling code here:
        String texto = textAreaPrincipal.getText();

        if (texto == null || !texto.trim().isEmpty()) {
            String entrada = textAreaPrincipal.getText();
            if (entrada != null && !entrada.trim().isEmpty()) {
                Lexico.scanner(entrada);
                executouAnalisadores = true;
                textAreaResultado.setText(Lexico.retornaToken());
                jMenuItem1.setVisible(false);

            } else {
                JOptionPane.showMessageDialog(null, "Digite ou importe o arquivo da linguagem LALG");
            }

            //panel2.setVisible(true);
            textAreaResultado.setText("");
            if (texto != null && !texto.trim().isEmpty()) {
                Lexico.scanner(texto);
                executouAnalisadores = true;
                String a = ListaErro.listaToString();

                //textAreaResultado.setText(a);
                textAreaResultado.setText(Lexico.retornaToken());

            } else {
                JOptionPane.showMessageDialog(null, "Digite ou importe o arquivo da linguagem LALG");
            }

        } else {
            JOptionPane.showMessageDialog(null, "Digite ou importe o arquivo da linguagem LALG");
        }
    }//GEN-LAST:event_buttonConstruirActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        OpenActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void buttonLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLimparActionPerformed
        // TODO add your handling code here:
        limpar();
    }//GEN-LAST:event_buttonLimparActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        String text = "Trabalho 1 e 2º Bimestres\nMatéria: Compiladores\n\nDocente:\nProf. Ms. Carlos Henrique Odenique Jardim \n\nAlunos:\nDanilo Stefaneli Cardoso\nMarco Antonio Queiroz\n\nVersão: 2.00.9876";
        //JOptionPane.showMessageDialog(null, );
        JOptionPane.showMessageDialog(null, text);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void buttonCompilarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCompilarActionPerformed
        textAreaResultado.setText("");
        String texto = textAreaPrincipal.getText();

        if (texto != null && !texto.trim().isEmpty()) {
            Sintatico.scanner(texto);
            executouAnalisadores = true;
            textAreaResultado.setText(ListaErro.listaToString());

        } else {
            JOptionPane.showMessageDialog(null, "Digite ou importe o arquivo da linguagem LALG");
        }
    }//GEN-LAST:event_buttonCompilarActionPerformed

    private void buttonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSalvarActionPerformed
        String texto = textAreaPrincipal.getText();

        if (!executouAnalisadores) {
            JOptionPane.showMessageDialog(null, "Execute algum analisador primeiramente.");
        } else {
            if (texto != null && !texto.trim().isEmpty()) {
                if (verificaCaminhoSaida()) {
                    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    fileChooser.showOpenDialog(this);
                    int returnVal = 0;
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        setCaminhoSaida(fileChooser.getSelectedFile().getAbsolutePath());
                        caminhoSaida.setText(fileChooser.getSelectedFile().getAbsolutePath());
                    }
                }
                String nomeSaida;
                if (nomeArquivo != null && !nomeArquivo.isEmpty()) {
                    nomeSaida = nomeArquivo.substring(0, nomeArquivo.length() - 4).concat("_resultado.txt");
                } else {
                    nomeSaida = "resultado.txt";
                }
                pathSaida = pathSaida.concat("\\".concat(nomeSaida));
                try {
                    File file = new File(pathSaida);
                    PrintWriter writer = new PrintWriter(file);
                    if (textAreaResultado != null) {
                        StringTokenizer resultado = new StringTokenizer(textAreaResultado.getText(), "\n");
                        while (resultado.hasMoreTokens()) {
                            String t = resultado.nextToken();
                            writer.println(t);
                        }
                        writer.flush();
                    } else {
                        JOptionPane.showMessageDialog(null, "Sem resultados!");
                    }
                    JOptionPane.showMessageDialog(null, "Arquivo salvo com sucesso.");
                    importouArquivo = false;
                } catch (FileNotFoundException ex) {
                }
            } else {
                JOptionPane.showMessageDialog(null, "Digite ou importe o arquivo da linguagem LALG");
            }
        }
    }//GEN-LAST:event_buttonSalvarActionPerformed

    private void caminhoSaidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_caminhoSaidaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_caminhoSaidaActionPerformed

    private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            arquivo = fileChooser.getSelectedFile();
            try {
                FileInputStream fis = new FileInputStream(arquivo);
                Scanner scanner = new Scanner(fis);
                StringBuilder builder = new StringBuilder();
                while (scanner.hasNextLine()) {
                    builder.append(scanner.nextLine()).append('\n');
                }
                if (builder.length() > 0) {
                    textAreaPrincipal.setText(builder.toString().trim());
                    builder.delete(0, builder.length());
                    receberArquivo(arquivo.getParent(), arquivo.getName());
                } else {
                    JOptionPane.showMessageDialog(null, "Arquivo vazio!");
                }
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(null, "Falha ao acessar o arquivo: " + arquivo.getPath());
                System.out.println("Falha ao acessar o arquivo: " + arquivo.getPath());
            }
        } else {
            JOptionPane.showMessageDialog(null, "Acesso ao arquivo cancelado pelo usuário.");
            System.out.println("Acesso ao arquivo cancelado pelo usuário.");
        }
    }

    public static void receberArquivo(String path, String nome) {
        importouArquivo = true;
        pathSaida = path;
        nomeArquivo = nome;
    }

    public static void setNullCaminhoSaida() {
        pathSaida = null;
    }

    public static void setCaminhoSaida(String path) {
        pathSaida = path;
    }

    public static boolean verificaCaminhoSaida() {
        return pathSaida == null;
    }

    class FiltroTexto extends javax.swing.filechooser.FileFilter {

        @Override
        public boolean accept(File file) {
            return file.isDirectory() || file.getAbsolutePath().endsWith(".txt");
        }

        @Override
        public String getDescription() {
            return "Arquivo de texto (*.txt)";
        }
    }

    /**
     * Função destinada a limpar os jtextarea da tela principal, e habilitar o
     * item de importar no menu arquivo.
     */
    public void limpar() {
        textAreaPrincipal.setText(null);
        textAreaResultado.setText(null);
        jMenuItem1.setVisible(true);
        setNullCaminhoSaida();
        executouAnalisadores = false;
        caminhoSaida.setText(null);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaPrincipal().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCompilar;
    private javax.swing.JButton buttonConstruir;
    private javax.swing.JButton buttonLimpar;
    private javax.swing.JButton buttonSalvar;
    private javax.swing.JTextField caminhoSaida;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private java.awt.Label label1;
    private javax.swing.JPanel panel1;
    private javax.swing.JTextPane textAreaPrincipal;
    private javax.swing.JTextArea textAreaResultado;
    // End of variables declaration//GEN-END:variables
}
